import React from 'react';
import {connect} from 'react-redux';
import {Table, Badge, Button, message} from 'antd';
import {messages} from "share/common";
import SlideFrame from 'components/slide-frame'
import  EmailNotificationService from 'containers/setting/email-notification/email-notification.service'
import NewEmailNotification from 'containers/setting/email-notification/new-email-notification'
import ResizeTable from "components/resize-table";

class EmailNotification extends React.Component {
  constructor(props) {
    super(props);

    this.state = {
      loading: true,
      data: [],
      page: 0,
      pageSize: 10,
      columns: [
        {title: messages('common.sequence'/*序号*/), dataIndex: 'index', width: 48},
        {title: messages('setting.key485'/*单据类型*/), dataIndex: 'formTypeDesc'},
        {
          title: messages('setting.key486'/*适用公司*/),
          dataIndex: 'customCompanyRelationResps',
          width: '40%',
          render: (value, item) => {
            return this.renderIsAll(value, item)
          }
        },
        {
          title: messages('common.column.status'/*状态*/), dataIndex: 'valid',
          render: valid =>
            <Badge status={valid ? 'success' : 'error'}
                   text={valid ? messages('common.status.enable') : messages('common.status.disable')}/>
        },
        {
          title: messages('setting.key487'/*最近更新时间*/), dataIndex: 'lastModifiedDate', width: '20%',
          render: date => new Date(date).format('yyyy-MM-dd hh:mm')
        },
      ],
      pagination: {
        total: 0,
        validNum: 0,
        disableNum: 0,
      },
      updateParams: {},
      showSlideFrameNew: false,
    };
  }

  componentWillMount() {
    this.getList();
  }

  renderIsAll = (value, item) => {
    let arr =[];
    if (value) {
      value.forEach(list => {
        arr.push(list.name)
      });
    }
    return (item.visibleCompanyScope === 1 ? messages('common.all')/*全部*/ : arr.join('、')  )
  }

  //得到列表数据
  getList() {
    this.setState({loading: true});
    let param = {
      page: this.state.page,
      size: this.state.pageSize,
    }
    EmailNotificationService.getDeptGroupByOptions(param).then((response) => {
      response.data.map((item, index) => {
        item.key = item.id;
        item.index = index + this.state.page * this.state.pageSize + 1;
      });
      this.setState({
        data: response.data,
        loading: false,
        pagination: {
          total: Number(response.headers['x-total-count']) ? Number(response.headers['x-total-count']) : 0,
          validNum: Number(response.headers['x-valid-count']) ? Number(response.headers['x-valid-count']) : 0,
          disableNum: Number(response.headers['x-invalid-count']) ? Number(response.headers['x-invalid-count']) : 0,
          onChange: this.onChangePager,
          current: this.state.page + 1
        }
      })
    }).catch((e) => {
      if (e.response) {
        message.error(`${e.response.data.message}`);
      }
      this.setState({loading: false});
    })
  }

  //分页点击
  onChangePager = (page) => {
    if (page - 1 !== this.state.page)
      this.setState({
        page: page - 1,
        loading: true
      }, () => {
        this.getList();
      })
  };


  handleCloseNewSlide = (params) => {
    this.setState({
      showSlideFrameNew: false
    }, () => {
      this.getList();
    })
  };

  showSlideNew = (flag) => {
    this.setState({
      showSlideFrameNew: flag
    })
  };

  editItem = (record) => {
    this.setState({
      showSlideFrameNew: true,
      updateParams: record,

    }, () => {
      this.showSlideNew(true)
    })
  };

  newItemShowSlide = () => {
    this.setState({
      updateParams: {},
      showSlideFrameNew: true,
    }, () => {
      this.showSlideNew(true)
    })
  }

  render() {

    const {
      columns, data, loading, pagination, updateParams,
      showSlideFrameNew
    } = this.state;
    return (
      <div className="budget-organization">

        <h3 className="header-title">
          {messages('setting.key488'/*打印邮件通知*/)}
        </h3>

        <div className="table-header">
          <div className="table-header-title">
            {messages('common.total', {total: pagination.total ? pagination.total : '0'})}，
            {messages('setting.key1451',{arg1: pagination.validNum ? pagination.validNum : '0'}/*启用 {arg1} 条*/)}，
            {messages('setting.key1452',{arg1: pagination.disableNum ? pagination.disableNum : '0'}/*禁用 {arg1} 条*/)}
          </div>
          {/* 共total条数据 */}
          {this.props.tenantMode && <div className="table-header-buttons">
            <Button type="primary"
                    onClick={this.newItemShowSlide}>
              {/*新建*/}
              {messages('common.create')}</Button>

          </div>}
        </div>
        <ResizeTable
          columns={columns}
          onRow={(record) => {
            return {
              onClick: () => {this.editItem(record)},       // 点击行
            };
          }}
          dataSource={data}
          pagination={pagination}
          loading={loading}
          bordered
          size="middle"
        />
        {/*新建编辑消息*/}
        { showSlideFrameNew && <SlideFrame title={JSON.stringify(updateParams) === "{}" ?
          messages('setting.key489'/*新建邮件通知*/) : messages('setting.key490'/*编辑邮件通知*/)}
                                           show={showSlideFrameNew}
                                           content={NewEmailNotification}
                                           afterClose={this.handleCloseNewSlide}
                                           onClose={() => this.setState({showSlideFrameNew: false})}
                                           params={updateParams}/>}
      </div>
    )
  }

}

EmailNotification.contextTypes = {
  router: React.PropTypes.object
};

function mapStateToProps(state) {
  return {
    tenantMode: state.main.tenantMode,
  }
}

export default connect(mapStateToProps)(EmailNotification);
